package lyj.springcloud.system;

import com.alibaba.druid.util.StringUtils;
import com.lyj.threads.ThreadPoolManage;
import com.lyj.units.Check;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import javax.annotation.PreDestroy;
import javax.annotation.Resource;

/**
 * 系统启动初始化类
 */
@Component
@Order(1)// 值越小，执行越早
public class SystemInit implements CommandLineRunner {

    /**
     * 读取配置的线程池配置
     */
    @Value("${threadPoolParam.profiles}")
    private String threadPoolParam;

    @Resource
    private Environment environment;


    /*
        CommandLineRunner接口作用：
            平常开发中有可能需要实现在项目启动后执行的功能，SpringBoot提供的一种简单的实现方案就是添加一个model并实现CommandLineRunner接口，
            实现功能的代码放在实现的run方法中也就是项目一启动之后，就立即需要执行的动作。
     */
    @Override
    public void run(String... args) throws Exception {
        System.out.println("》》》》》》》》》》》》》》》初始化代码《《《《《《《《《《《《《《《《《");
        String[] activeProfiles = environment.getActiveProfiles();
        // 初始化线程池
        initThreadPool();
    }

    /**
     * 初始化线程池
     */
    public void initThreadPool() {
        // 核心线程数
        String coreSize ;
        // 最大线程数
        String maxSize;
        // 队列数
        String queueSize;

        if (!Check.isEmpty(threadPoolParam)) {
            String[] profiles = threadPoolParam.split(",");
            for (int i = 0; i < profiles.length ;i++) {
                if (StringUtils.equals(profiles[i],"CONSUMER")) {
                    coreSize = environment.getProperty("threadPoolParam.params." + profiles[i] + ".core");
                    maxSize = environment.getProperty("threadPoolParam.params." + profiles[i] + ".max");
                    queueSize = environment.getProperty("threadPoolParam.params." + profiles[i] + ".queue");
                    try{
                        if (Check.isDigit(coreSize) && Check.isDigit(maxSize) && Check.isDigit(queueSize)) {
                            // 初始化线程
                            ThreadPoolManage.initPoolParam(profiles[i],coreSize , maxSize, queueSize);
                        }
                    }catch (Exception e) {
                        e.printStackTrace();
                        System.out.println("》》》》》》》》》》》》》初始化线程池异常《《《《《《《《《《《《《");
                    }
                }
            }

        }
    }

    /**
     *  @PreDestroy： 此注解会在在关闭spring容器后释放一些资源
     */
    @PreDestroy
    public void destroy() {
        System.out.println("System destroy start ");
        ThreadPoolManage.shutDownPool();
        System.out.println("System destroy end ");
    }
}
